<template>
  <div class="chat-assistant">
    <div class="header">
      <h1>{{ title }}</h1>
      <p>{{ subtitle }}</p>
    </div>

    <div class="chat-container" ref="chatContainer">
      <div v-if="messages.length === 0" class="empty-state">
        <svg
          width="100"
          height="100"
          viewBox="0 0 24 24"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM13 17H11V15H13V17ZM13 13H11V7H13V13Z"
            fill="#94a3b8"
          />
        </svg>
        <p>{{ emptyStateText }}</p>
      </div>

      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.sender]"
      >
        <div class="message-content">
          {{ message.text }}
        </div>
      </div>

      <div v-if="isTyping" class="message ai">
        <div class="message-typing">
          <div class="typing-dots">
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
          </div>
        </div>
      </div>
    </div>

    <div class="input-container">
      <!-- <input
        v-model="userInput"
        @keyup.enter="sendMessage"
        class="message-input"
        :placeholder="placeholder"
        :disabled="isTyping || disabled"
      />
      <button
        @click="sendMessage"
        class="send-button"
        :disabled="!userInput || isTyping || disabled"
      > -->
      <!-- <svg
          class="send-icon"
          viewBox="0 0 24 24"
          fill="white"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z" />
        </svg> -->
      <!-- </button> -->
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, onMounted, nextTick, computed } from 'vue';

  // 类型定义
  interface Message {
    text: string;
    sender: 'user' | 'ai' | 'system';
    timestamp?: string;
  }

  interface ApiConfig {
    endpoint: string;
    headers?: Record<string, string>;
    method?: string;
  }

  // Props 定义
  const props = withDefaults(
    defineProps<{
      title?: string;
      subtitle?: string;
      placeholder?: string;
      emptyStateText?: string;
      disabled?: boolean;
      autoScroll?: boolean;
      showWelcome?: boolean;
      apiConfig?: ApiConfig;
      initialMessages?: Message[];
    }>(),
    {
      title: 'AI智能助手',
      subtitle: '我可以回答您的问题并提供帮助',
      placeholder: '输入您的问题...',
      emptyStateText: '您好！我是您的AI助手，请问有什么可以帮您？',
      disabled: false,
      autoScroll: true,
      showWelcome: true,
      apiConfig: () => ({
        endpoint: '',
        headers: {},
        method: 'POST',
      }),
      initialMessages: () => [],
    }
  );

  // Emits 定义
  const emit = defineEmits<{
    (e: 'message-sent', message: string): void;
    (e: 'response-received', response: string): void;
    (e: 'error', error: Error): void;
    (e: 'update:messages', messages: Message[]): void;
    (e: 'typing-start'): void;
    (e: 'typing-end'): void;
  }>();

  // Refs
  // const userInput = ref('');
  const messages = ref<Message[]>([]);
  const isTyping = ref(false);
  const chatContainer = ref<HTMLElement | null>(null);

  // Computed
  // const hasApiEndpoint = computed(() => Boolean(props.apiConfig?.endpoint));

  const scrollToBottom = (): void => {
    nextTick(() => {
      if (chatContainer.value) {
        chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
      }
    });
  };
  
  const addMessage = (text: string, sender: 'user' | 'ai' | 'system'): void => {
    messages.value.push({
      text,
      sender,
      timestamp: new Date().toISOString(),
    });

    if (props.autoScroll) {
      scrollToBottom();
    }
  };

  // 初始化
  onMounted(() => {
    messages.value = [...props.initialMessages];
    if (props.showWelcome && messages.value.length === 0) {
      addMessage(props.emptyStateText, 'ai');
    }
    scrollToBottom();
  });

  // Watchers
  watch(
    () => messages.value,
    (newMessages) => {
      emit('update:messages', newMessages);
    },
    { deep: true }
  );

  watch(
    () => props.initialMessages,
    (newMessages) => {
      messages.value = [...newMessages];
    },
    { deep: true }
  );

  // const callApi = async (userMessage: string): Promise<string> => {
  //   const response = await fetch(props.apiConfig!.endpoint, {
  //     method: props.apiConfig!.method || 'POST',
  //     headers: {
  //       'Content-Type': 'application/json',
  //       ...props.apiConfig!.headers,
  //     },
  //     body: JSON.stringify({
  //       message: userMessage,
  //       timestamp: new Date().toISOString(),
  //     }),
  //   });

  //   if (!response.ok) {
  //     throw new Error(`API请求失败: ${response.status}`);
  //   }

  //   const data = await response.json();
  //   return data.reply || data.message || data.text || '收到消息，但无回复内容';
  // };

  // const getMockResponse = async (userMessage: string): Promise<string> => {
  //   // 模拟网络延迟
  //   await new Promise((resolve) =>
  //     setTimeout(resolve, 800 + Math.random() * 700)
  //   );

  //   const lowerMessage = userMessage.toLowerCase();

  //   if (lowerMessage.includes('你好') || lowerMessage.includes('hello')) {
  //     return '您好！很高兴为您服务。请问有什么可以帮您？';
  //   } else if (lowerMessage.includes('名字') || lowerMessage.includes('谁')) {
  //     return '我是一个AI助手，专门设计来回答您的问题和提供帮助。';
  //   } else if (lowerMessage.includes('时间')) {
  //     return '当前时间是：' + new Date().toLocaleTimeString();
  //   } else if (lowerMessage.includes('天气')) {
  //     return '抱歉，我目前无法获取实时天气信息。您可以尝试使用专业的天气应用或网站。';
  //   } else {
  //     return '感谢您的消息。我会尽力为您提供帮助，如果您需要更专业的协助，请告诉我更多细节。';
  //   }
  // };

  // const getAIResponse = async (userMessage: string): Promise<string> => {
  //   isTyping.value = true;
  //   emit('typing-start');

  //   try {
  //     if (hasApiEndpoint.value) {
  //       return await callApi(userMessage);
  //     } else {
  //       return await getMockResponse(userMessage);
  //     }
  //   } finally {
  //     isTyping.value = false;
  //     emit('typing-end');
  //   }
  // };

  // 方法
  // const sendMessage = async (): Promise<void> => {
  //   if (!userInput.value.trim() || isTyping.value || props.disabled) return;

  //   const userMessage = userInput.value.trim();
  //   addMessage(userMessage, 'user');
  //   userInput.value = '';

  //   emit('message-sent', userMessage);

  //   try {
  //     const aiResponse = await getAIResponse(userMessage);
  //     addMessage(aiResponse, 'ai');
  //     emit('response-received', aiResponse);
  //   } catch (error) {
  //     console.error('获取AI响应失败:', error);
  //     addMessage('抱歉，我暂时无法响应您的请求，请稍后再试。', 'ai');
  //     emit('error', error as Error);
  //   }
  // };

  // 暴露给父组件的方法
  const clearMessages = (): void => {
    messages.value = [];
    if (props.showWelcome) {
      addMessage(props.emptyStateText, 'ai');
    }
  };

  const addSystemMessage = (text: string): void => {
    addMessage(text, 'system');
  };

  // const triggerResponse = async (userMessage: string): Promise<string> => {
  //   addMessage(userMessage, 'user');
  //   emit('message-sent', userMessage);

  //   try {
  //     const aiResponse = await getAIResponse(userMessage);
  //     addMessage(aiResponse, 'ai');
  //     emit('response-received', aiResponse);
  //     return aiResponse;
  //   } catch (error) {
  //     console.error('获取AI响应失败:', error);
  //     addMessage('抱歉，我暂时无法响应您的请求，请稍后再试。', 'ai');
  //     emit('error', error as Error);
  //     throw error;
  //   }
  // };

  // 暴露方法给父组件
  defineExpose({
    clearMessages,
    addSystemMessage,
    // triggerResponse,
    addMessage,
    scrollToBottom,
  });
</script>

<style scoped>
  .chat-assistant {
    width: 100%;
    height: 100%;
    background: white;
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .header {
    background: linear-gradient(90deg, #4f46e5, #7c3aed);
    color: white;
    padding: 20px;
    text-align: center;
  }

  .header h1 {
    font-size: 24px;
    margin-bottom: 5px;
  }

  .header p {
    opacity: 0.9;
    font-size: 14px;
  }

  .chat-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f8fafc;
  }

  .message {
    margin-bottom: 20px;
    display: flex;
    animation: fadeIn 0.3s ease;
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .message.user {
    justify-content: flex-end;
  }

  .message-content {
    max-width: 70%;
    padding: 12px 16px;
    border-radius: 18px;
    line-height: 1.5;
    word-break: break-word;
  }

  .ai .message-content {
    background: white;
    border: 1px solid #e2e8f0;
    border-bottom-left-radius: 4px;
  }

  .user .message-content {
    background: #4f46e5;
    color: white;
    border-bottom-right-radius: 4px;
  }

  .system .message-content {
    background: #fffbeb;
    border: 1px solid #fef3c7;
    color: #92400e;
    font-style: italic;
  }

  .message-typing {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 18px;
    border-bottom-left-radius: 4px;
    max-width: 120px;
  }

  .typing-dots {
    display: flex;
  }

  .typing-dot {
    width: 8px;
    height: 8px;
    background: #94a3b8;
    border-radius: 50%;
    margin: 0 3px;
    animation: typingAnimation 1.4s infinite;
  }

  .typing-dot:nth-child(2) {
    animation-delay: 0.2s;
  }

  .typing-dot:nth-child(3) {
    animation-delay: 0.4s;
  }

  @keyframes typingAnimation {
    0%,
    60%,
    100% {
      transform: translateY(0);
    }
    30% {
      transform: translateY(-5px);
    }
  }

  .input-container {
    padding: 20px;
    background: white;
    border-top: 1px solid #e2e8f0;
    display: flex;
    gap: 10px;
  }

  .message-input {
    flex: 1;
    padding: 12px 16px;
    border: 1px solid #e2e8f0;
    border-radius: 24px;
    outline: none;
    font-size: 16px;
    transition: border-color 0.3s;
  }

  .message-input:focus {
    border-color: #4f46e5;
  }

  .send-button {
    background: #4f46e5;
    color: white;
    border: none;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: background 0.3s;
  }

  .send-button:hover {
    background: #4338ca;
  }

  .send-button:disabled {
    background: #cbd5e1;
    cursor: not-allowed;
  }

  .send-icon {
    width: 24px;
    height: 24px;
  }

  .empty-state {
    text-align: center;
    color: #94a3b8;
    padding: 40px 20px;
  }

  .empty-state svg {
    margin-bottom: 20px;
    opacity: 0.7;
  }

  @media (max-width: 600px) {
    .message-content {
      max-width: 85%;
    }

    .header {
      padding: 15px;
    }

    .header h1 {
      font-size: 20px;
    }
  }
</style>